package com.xdl.flytest.controller;

import com.xdl.flytest.bean.Environment;
import com.xdl.flytest.service.EnvironmentService;
import com.xdl.flytest.util.JsonResponseMessage;
import com.xdl.flytest.util.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @Auther: 80736
 * @Date: 2019/1/4 20:19
 * @Description:
 */
@Controller
@RequestMapping("/env")
public class EnvironmentController {
    @Autowired
    private EnvironmentService environmentService;


    @GetMapping("/")
    public ModelAndView envIndex() {
        List<Environment> environments = environmentService.getEnvironments();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("envs", environments);
        modelAndView.setViewName("env/page-env");
        return modelAndView;
    }

    @GetMapping("/environment")
    @ResponseBody
    public Map<String, Object> getEnv(@RequestParam("envId") Integer envId) {
        Environment environment = environmentService.getEnvironmentById(envId);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).addAttribute("env", environment).returned();
    }

    @PostMapping("/environment")
    @ResponseBody
    public Map<String, Object> addEnv(@Validated Environment environment, BindingResult result) {
        if (result.hasErrors()) {
            return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR)
                    .addAttribute("error", result.getFieldError().getDefaultMessage())
                    .returned();
        }
        environmentService.addEnv(environment);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    @PutMapping("/environment")
    @ResponseBody
    public Map<String, Object> updateEnv(@Validated Environment environment, BindingResult result) {
        if (result.hasErrors()) {
            return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR)
                    .addAttribute("error", result.getFieldError().getDefaultMessage())
                    .returned();
        }
        environmentService.updateEnv(environment);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    @DeleteMapping("/environment")
    @ResponseBody
    public Map<String, Object> deleteEnv(@RequestParam("envId") Integer envId) {
        environmentService.deleteEnvById(envId);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

}
